package me.xingyannian.hope.rest;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import me.xingyannian.hope.entity.User;
import me.xingyannian.hope.service.UserService;
import me.xingyannian.hope.util.MyTokenInfo;
import me.xingyannian.hope.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {
    private UserService userService;

    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping
    public SaResult login(@RequestBody UserVo userVo){
        User user = this.userService.getUserByLoginId(userVo.getLoginId());
        if (null != user ){
            if (user.getPassword().equals(userVo.getPassword())){
                // 第1步，先登录上
                System.out.println(user.getLoginId());
                StpUtil.login(user.getLoginId());
                // 第2步，获取 Token  相关参数
                SaTokenInfo saTokenInfo = StpUtil.getTokenInfo();
                // 第3步，返回给前端
                MyTokenInfo myTokenInfo = new MyTokenInfo();
                myTokenInfo.setUserName(user.getName());
                BeanUtils.copyProperties(saTokenInfo , myTokenInfo);
                return SaResult.data(myTokenInfo);
            }
            return SaResult.error("密码错误！");
        }
        return SaResult.error("用户名错误！");
    }

}
